<?php
namespace App\Http\Controllers\Business\Shop\V1\Auth;

use App\Models\ShopUser;
use App\Models\SmsMessage;
use Log;
use Illuminate\Support\Facades\Redis;

class ShopAuth {
    //登录
    public static function login($mobile,$code) {
        //TODO ios测试帐号
        if(env('WEB_URL') == 'https://test2.fbw-china.com/') {
            if (($mobile == '18888888888') && ($code=='777777')) {
                $userId = ShopUser::where('mobile', $mobile)->pluck('id')->first();
                return ['status' => 'success', 'data' => ['token' => self::getToken($userId)]];
            }
        } else {
            if ($mobile == '18888888888') {
                $userId = ShopUser::where('mobile', $mobile)->pluck('id')->first();
                return ['status' => 'success', 'data' => ['token' => self::getToken($userId)]];
            }
        }
        if(!$mobile || !$code) {
            return ['status'=>'failed','message'=>'请求数据不完整！'];
        }
        if(!SmsMessage::loginIdentifyingCodeVerify($mobile,$code,'2')) {
            return ['status'=>'failed','message'=>'验证码错误！'];
        }
        $userId = ShopUser::where('mobile', $mobile)->pluck('id')->first();
        if($userId) {
            $user = ShopUser::find($userId);
            $user->logintime=date('Y-m-d H:i:s',time());
            $user->save();
            $token = self::getToken($userId);
            if($token == false) {
                return ['status'=>'failed', 'message'=>'认证失败，重新登录'];
            }
            return ['status'=>'success','data'=>['token'=>$token]];
        } else {
            return ['status'=>'failed','message'=>'身份验证失败，您还不是我们的商户，请先申请入驻！'];
        }
    }
    //版本12的登录
    public static function loginByV12Version($mobile, $type, $code='', $password='') {
        if(!$mobile || (strlen($mobile) != 11) || !$type){
            return ['status'=>'failed','message'=>'参数错误'];
        }
        //判断传过来的是密码还是验证码
        if($type == 'sms'){
            if(!$mobile || !$code){
                return ['status'=>'failed','message'=>'请求参数不完整'];
            }
            //ios测试帐号
            if(env('WEB_URL') == 'https://test2.fbw-china.com/') {
                if (($mobile == '18888888888') && ($code=='777777')) {
                    $userId = ShopUser::where('mobile', $mobile)->pluck('id')->first();
                    return ['status' => 'success', 'data' => ['token' => self::getToken($userId)]];
                }
            } else {
                if ($mobile == '18888888888') {
                    $userId = ShopUser::where('mobile', $mobile)->pluck('id')->first();
                    return ['status' => 'success', 'data' => ['token' => self::getToken($userId)]];
                }
            }
            if(!SmsMessage::loginIdentifyingCodeVerify($mobile,$code,'2')) {
                return ['status'=>'failed','message'=>'验证码错误！'];
            }
            $userId = ShopUser::where('mobile', $mobile)->where('status',1)->pluck('id')->first();
            if(!$userId) {
                return ['status'=>'failed','message'=>'身份验证失败，您还不是我们的商户，请先申请入驻！'];
            }
        }elseif($type == 'password'){
            if(!$mobile || !$password){
                return ['status'=>'failed','message'=>'请求参数不完整'];
            }
            //判断是否有密码
            $shopUser = ShopUser::where('mobile',$mobile)->where('status',1)->select('id','password')->first();
            if($shopUser){
                if($shopUser['password'] == ''){
                    return ['status'=>'failed','message'=>'未设置密码，请使用验证码登录'];
                }
                $getPassword = md5($password . env('PASSWORD_SALT'));
                if($getPassword != $shopUser['password']){
                    return ['status'=>'failed','message'=>'手机号或密码错误'];
                }
                $userId = $shopUser['id'];
            }else{
                return ['status'=>'failed', 'message'=>'身份验证失败，您还不是我们的商户，请先申请入驻！'];
            }
        }else{
            return ['status'=>'failed','message'=>'身份验证失败，您还不是我们的商户，请先申请入驻！'];
        }
        //修改登录时间，并将ID以token的形式传给移动端
        $user = ShopUser::find($userId);
        $user->logintime=date('Y-m-d H:i:s',time());
        $user->save();
        $token = self::getToken($userId);
        if($token == false) {
            return ['status'=>'failed', 'message'=>'认证失败，重新登录'];
        }
        return ['status'=>'success','data'=>['token'=>$token]];
    }
    //获取验证码
    public static function getCode($mobile, $mode, $sub='') {
        if(!$mobile||!$mode) {
            return ['status'=>'failed','message'=>'请求数据不完整！'];
        }
        if($sub != '1') {
            //sub 用来区分是不是添加子账号（1），还是登录（0）
            $shopauth = ShopUser::where('mobile', $mobile)->pluck('auth')->first();
            if (!$shopauth || $shopauth == '[]') {
                return ['status' => 'failed', 'message' => '身份验证失败，您还不是我们的商户，请先申请入驻！'];
            }
        }
        if($mobile == '18888888888') {
            //测试
            return ['status'=>'success','message'=>'验证码发送成功！'];
        }
        if (SmsMessage::loginIdentifyingCode($mobile,'2',$mode)){
            return ['status'=>'success','message'=>'验证码发送成功！'];
        }else {
            return ['status'=>'failed','message'=>'验证码发送失败，请稍后再试！'];
        }
    }
    //获取token
    public static function getToken($userId) {
        if(!$userId) {
            return false;
        }
        if(ShopUser::where('id', $userId)->first()) {
            do{
                $token = self::getRandChar(128);
            } while(Redis::get('ShopApiToken:' . $token));
            if (Redis::get('ShopApiToken:UserId:' . $userId)) {
                Redis::del('ShopApiToken:' . Redis::get('ShopApiToken:UserId:' . $userId));
            }
            Redis::setex('ShopApiToken:' . $token, 2592000, $userId);
            Redis::setex('ShopApiToken:UserId:' . $userId, 2592000, $token);
            return $token;
        }
        return false;
    }
    //获取随机数
    static function getRandChar($length) {
        $str = null;
        $strPol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
        $max = strlen($strPol)-1;

        for($i=0;$i<$length;$i++){
            $str.=$strPol[rand(0,$max)];
        }

        return $str;
    }
    //通过userid 获取token
    public static function tokenGetUserId($token) {
        if(Redis::ttl('ShopApiToken:'.$token)<2505600)  {
            return false;
        }
        return Redis::get('ShopApiToken:'.$token);
    }
    //刷新token
    public static function refreshToken($token) {
        $userid=Redis::get('ShopApiToken:'.$token);
        if($userid) {
            Redis::del('ShopApiToken:'.$token);
            $token = self::getRandChar(128);
            if(Redis::get('ShopApiToken:'.$token)) {
                $token = self::getRandChar(128);
            }
            Redis::setex('ShopApiToken:'.$token,2592000,$userid);
            Redis::setex('ShopApiToken:UserId:'.$userid,2592000,$token);
            return $token;
        }
        return false;
    }

    public static function apiLogout($token) {
        $userid=Redis::get('ShopApiToken:'.$token);
        Redis::del('ShopApiToken:'.$token);
        Redis::del('ShopApiToken:UserId:'.$userid);
        return true;
    }
}